<!--
 * @Descripttion: 
 * @version: @ 1.0.0
 * @Author: 朱江洲
 * @Date: 2022-02-10 10:50:23
 * @LastEditors: 朱江洲
 * @LastEditTime: 2022-05-10 18:01:36
-->
<template>
  <div>
    <el-dialog
      title="新建合同"
      :visible.sync="dialog.newContactShow"
      width="50%"
      custom-class="conClass"
      @close="contactClose"
    >
      <el-form
        :model="contactForm"
        ref="contactForm"
        :rules="contactRules"
        label-position="top"
        :inline="false"
        size="normal"
        v-if="dialog.newContactShowEject"
      >
        <div class="basics">基础信息</div>
        <div class="formItem">
          <el-form-item label="合同名称" prop="name">
            <el-input
              v-model="contactForm.name"
              placeholder="请输入合同名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同编号" prop="code" v-if="numShow">
            <el-input
              v-model="contactForm.code"
              placeholder="请输入合同编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="客户名称" prop="customer">
            <el-input
              :disabled="payDisabled"
              v-model="contactForm.customer"
              placeholder="+ 添加"
              @focus="customerAdd"
            ></el-input>
          </el-form-item>
          <el-form-item label="商机名称">
            <el-input
              v-model="contactForm.opportunity"
              placeholder="+ 添加"
              @focus="businessAdd"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同金额" prop="amount">
            <el-input
              type="number"
              v-model="contactForm.amount"
              placeholder="请输入合同金额"
            ></el-input>
          </el-form-item>
          <el-form-item label="签约时间" prop="contractTime">
            <el-date-picker
              v-model="contactForm.contractTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="合同开始时间">
            <el-date-picker
              v-model="contactForm.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="合同结束时间">
            <el-date-picker
              v-model="contactForm.finishTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="客户签约人">
            <el-input
              v-model="contactForm.customerContract"
              placeholder="+ 添加"
              @focus="autographAdd"
            ></el-input>
          </el-form-item>
          <el-form-item label="公司签约人">
            <el-select
              v-model="contactForm.companyContractId"
              placeholder="请选择公司签约人"
            >
              <el-option
                v-for="item in options"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              rows="3"
              v-model="contactForm.remark"
              style="width: 330px"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同类型">
            <el-select v-model="contactForm.type" placeholder="请选择合同类型">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支出合同">
            <el-input
              v-model="contactForm.relateName"
              placeholder="+ 添加"
              @focus="expAdd"
            ></el-input>
          </el-form-item>
        </div>
        <div class="basics">审核信息</div>
        <el-form-item label="审核人" prop="examine">
          <div class="approve">
            <template v-for="(item, index) in examineList">
              <div :key="index" class="examine">
                <div class="examine-qd">
                  <div class="circle-img">
                    <el-tooltip
                      :content="item.nickName"
                      placement="top"
                      effect="dark"
                    >
                      <img :src="item.avatar" alt="" />
                    </el-tooltip>
                  </div>
                  <div>{{ item.nickName }}</div>
                  <div class="circle-series">第{{ index + 1 }}级</div>
                </div>
              </div>
            </template>
            <div class="examine">
              <div class="examine-qd">
                <div class="circle" @click="onAdd">
                  <i class="el-icon-plus circleIcon"></i>
                </div>
                <div>选择人员</div>
                <div class="circle-series">
                  第{{ examineList.length + 1 }}级
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div class="mainCustom">
        <div
          v-for="(item, index) in formList"
          :key="index"
          :class="item.type !== 18 ? 'mainCustomFive' : 'mainCustomOne'"
        >
          <div v-show="item.isHidden">
            <main-content
              :formList="item"
              class="main-con"
              ref="mainContent"
            ></main-content>
          </div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="dialog.newContactShow = false">取消</el-button>
        <el-button
          @click="draftSubmit"
          v-if="contactForm.status == undefined || contactForm.status == 0"
          >保存为草稿</el-button
        >
        <el-button type="primary" @click="submit">提交审核</el-button>
      </span>
    </el-dialog>
    <customer :dialog="dialog"></customer>
    <opportunity :dialog="dialog" v-if="dialog.OpportunityEject"></opportunity>
    <customer-contract
      :dialog="dialog"
      v-if="dialog.customerContractShowEject"
    ></customer-contract>
    <el-dialog title="审核人" :visible.sync="dialog.examineShow" width="30%">
      <el-table :data="examineData" @selection-change="handleSelectionChange">
        <el-table-column type="selection"> </el-table-column>
        <el-table-column prop="nickName" label="审核人名称"> </el-table-column>
      </el-table>

      <span slot="footer">
        <el-button @click="dialog.examineShow = false">取消</el-button>
        <el-button type="primary" @click="examineSubmit" :disabled="disabled"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <div v-if="dialog.expenditureShowEject">
      <el-dialog
        title="关联支出合同模块"
        :visible.sync="dialog.expenditureShow"
        width="60%"
        :modal="false"
        custom-class="conClass"
        @close="expClose"
      >
        <expenditure-con ref="expCon" :viewShow="viewShow"></expenditure-con>
        <span slot="footer">
          <el-button @click="dialog.expenditureShow = false">取消</el-button>
          <el-button type="primary" @click="expSubmit">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getNoRepeatPersonLiable,
  insert,
  updateInsert,
  insertDraft,
} from "@/api/CRM/comtact";
import { distriBution } from "@/api/registration"; //获取负责人接口
import customer from "./CRM/customer.vue";
import CustomerContract from "./CRM/customerContract.vue";
import Opportunity from "./CRM/opportunity.vue";
import { getModuleByName, showCustomField } from "@/api/currency.js";
import { showCodeInput } from "@/api/sys";
import mainContent from "@/components/mainContent/index.vue";
import expenditureCon from "../../expContract/index";
export default {
  name: "newCon",
  components: {
    customer,
    Opportunity,
    CustomerContract,
    mainContent,
    expenditureCon,
  },
  props: {
    dialog: {
      type: Object,
      required: true,
    },
    payDisabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateExamine = (rule, value, callback) => {
      if (this.contactForm.auditUserIds.length == 0) {
        callback(new Error("请选择审核人"));
      } else {
        callback();
      }
    };
    return {
      viewShow: false,
      numShow: true,
      formList: [],
      disabled: false,
      multipleSelection: [],
      examineData: [],
      typeOptions: [
        {
          value: 1,
          label: "新合同",
        },
        {
          value: 2,
          label: "续约合同",
        },
      ],
      examineList: [],
      options: [],
      contactForm: {
        name: "",
        code: "",
        customerId: "",
        customer: "",
        opportunityId: "",
        opportunity: "",
        amount: "",
        type: "",
        contractTime: "",
        startTime: "",
        finishTime: "",
        customerContractId: "",
        customerContract: "",
        companyContractId: "",
        remark: "",
        auditUserIds: [],
        relateId: "",
        relateName: "",
      },
      contactRules: {
        name: [{ required: true, message: "请输入合同名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入合同编号", trigger: "blur" }],
        customer: [{ required: true, message: "请输入客户名称" }],
        amount: [
          { required: true, message: "请输入合同金额", trigger: "blur" },
        ],
        contractTime: [
          { required: true, message: "请选择签约时间", trigger: "change" },
        ],
        examine: [
          {
            required: true,
            message: "请选择审核人",
            validator: validateExamine,
          },
        ],
      },
    };
  },
  created() {
    this.getDistri();
    this.getModule();
    this.showCodeInput();
  },
  methods: {
    // 关闭绑定支出合同
    expClose() {
      this.dialog.expenditureShowEject = false;
    },
    // 确定绑定
    expSubmit() {
      if (this.$refs["expCon"].multipleSelection.length > 1)
        return this.$message.info("只允许绑定一个合同！");
      this.contactForm.relateId = this.$refs["expCon"].multipleSelection[0].id;
      this.contactForm.relateName =
        this.$refs["expCon"].multipleSelection[0].name;
      this.dialog.expenditureShow = false;
    },
    // 绑定支出合同
    expAdd() {
      this.dialog.expenditureShowEject = true;
      this.$nextTick(() => {
        this.dialog.expenditureShow = true;
      });
    },
    // 是否展示合同编号
    showCodeInput() {
      showCodeInput({
        module: 1,
      }).then((res) => {
        this.numShow = res.data;
      });
    },
    // 获取模块Id
    getModule() {
      getModuleByName({
        name: "合同",
      }).then((res) => {
        showCustomField({
          module: res.data,
          id: this.contactForm.id || null,
        }).then((res) => {
          console.log(res);
          res.data.map((item) => {
            if (item.type == 3 && item.choiceList == null) {
              item.choiceList = [];
              console.log(item);
            }
          });
          this.formList = res.data;
          console.log(this.formList);
        });
      });
    },
    // 表格前多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (val.length > 1) {
        this.disabled = true;
      } else {
        this.disabled = false;
      }
    },
    // 审核人确定
    examineSubmit() {
      this.contactForm.auditUserIds.push(this.multipleSelection[0].userId);
      this.examineList.push(this.multipleSelection[0]);
      this.dialog.examineShow = false;
      this.multipleSelection = [];
    },
    // 获取审核
    getNoRepeatPersonLiable() {
      getNoRepeatPersonLiable(this.contactForm.auditUserIds).then((res) => {
        this.examineData = res.data;
      });
    },
    // 获取负责人
    getDistri() {
      distriBution().then((res) => {
        this.options = res.data;
      });
    },
    // 客户添加
    customerAdd() {
      this.dialog.customerShow = true;
    },
    // 商机添加
    businessAdd() {
      if (this.contactForm.customerId == "") {
        this.$message.info("请先选择客户名称");
      } else {
        this.dialog.OpportunityEject = true;
        this.$nextTick(function () {
          this.dialog.OpportunityShow = true;
        });
      }
    },
    // 签约人添加
    autographAdd() {
      if (this.contactForm.customerId == "") {
        this.$message.info("请先选择客户名称");
      } else {
        this.dialog.customerContractShowEject = true;
        this.$nextTick(function () {
          this.dialog.customerContractShow = true;
        });
      }
    },
    // 添加审核人员
    onAdd() {
      this.dialog.examineShow = true;
      this.getNoRepeatPersonLiable();
    },
    // 保存为草稿
    draftSubmit() {
      this.contactForm.customField = JSON.stringify(this.formList);
      this.$refs.contactForm.validate((valid) => {
        if (!valid) return;
        insertDraft(this.contactForm).then((res) => {
          this.$message.success(res.msg);
          this.$parent.getList();
          if (this.payDisabled == true) {
            this.$parent.contractList();
          }
          this.dialog.newContactShow = false;
        });
      });
    },
    // 提交审核
    submit() {
      this.contactForm.customField = JSON.stringify(this.formList);
      console.log(this.contactForm.auditUserIds);
      this.$refs.contactForm.validate((valid) => {
        if (!valid) return;
        if (this.contactForm.id == null) {
          insert(this.contactForm).then((res) => {
            this.$message.success(res.msg);
            this.$parent.getList();
            if (this.payDisabled == true) {
              this.$parent.contractList();
            }
            this.dialog.newContactShow = false;
          });
        } else {
          updateInsert(this.contactForm).then((res) => {
            this.$message.success(res.msg);
            this.$parent.getList();
            this.dialog.newContactShow = false;
          });
        }
      });
    },
    // 关闭新建合同
    contactClose() {
      this.contactForm = {
        name: "",
        code: "",
        customerId: "",
        customer: "",
        opportunityId: "",
        opportunity: "",
        amount: "",
        type: "",
        contractTime: "",
        startTime: "",
        finishTime: "",
        customerContractId: "",
        customerContract: "",
        companyContractId: "",
        remark: "",
        auditUserIds: [],
      };
      this.numShow = true;
      this.dialog.newContactShowEject = false;
    },
  },
};
</script>

<style lang="less" scoped>
.basics {
  position: relative;
  font-size: 14px;
}
.basics::before {
  content: "";
  position: absolute;
  left: -6px;
  top: 1px;
  width: 3px;
  height: 14px;
  background: #1267fa;
}
/deep/ .conClass {
  .el-dialog__body {
    height: 720px;
    overflow-y: auto;
  }
}
.formItem {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  .el-form-item {
    width: 50%;
    /deep/.el-input__inner {
      width: 330px;
    }
  }
}
.approve {
  display: flex;
  flex-wrap: wrap;
}
.examine {
  display: flex;
  margin-right: 20px;
  padding: 0 5px;
  .examine-qd {
    display: flex;
    flex-direction: column;
    align-items: center;
    .circle-img {
      width: 40px;
      height: 40px;
      border-radius: 40px;
      img {
        width: 100%;
        height: 100%;
        border-radius: 40px;
      }
    }
    .circle {
      width: 40px;
      height: 40px;
      border-radius: 40px;
      background-color: #1267fa;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      .circleIcon {
        color: #fff;
        font-size: 18px;
      }
    }
  }
}
.mainCustom {
  display: flex;
  flex-wrap: wrap;
  .mainCustomFive {
    width: 50%;
  }
  .mainCustomOne {
    width: 100%;
  }
}
</style>